package com.pt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pt.common.CommonResult;
import com.pt.dto.request.SendMessageRequest;
import com.pt.dto.response.PrivateMessageResponse;
import com.pt.entity.PrivateMessage;
import com.pt.entity.User;
import com.pt.service.PrivateMessageService;
import com.pt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "私信管理")
@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
public class PrivateMessageController {
    
    private final PrivateMessageService privateMessageService;
    private final UserService userService;
    
    @ApiOperation("获取收件箱")
    @GetMapping("/inbox")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<Page<PrivateMessageResponse>> getInbox(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size,
            HttpServletRequest request) {
        
        User user = userService.getCurrentUser();
        
        Page<PrivateMessage> pageParam = new Page<>(page, size);
        IPage<PrivateMessage> messages = privateMessageService.getInbox(user.getId(), pageParam);
        
        // 转换为响应DTO
        List<PrivateMessageResponse> responseList = messages.getRecords().stream()
            .map(this::convertToResponse)
            .collect(Collectors.toList());
            
        Page<PrivateMessageResponse> responsePage = new Page<>(page, size, messages.getTotal());
        responsePage.setRecords(responseList);
        
        return CommonResult.success(responsePage);
    }
    
    @ApiOperation("获取发件箱")
    @GetMapping("/outbox")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<Page<PrivateMessageResponse>> getOutbox(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer page,
            @ApiParam("每页数量") @RequestParam(defaultValue = "20") Integer size,
            HttpServletRequest request) {
        
        User user = userService.getCurrentUser();
        
        Page<PrivateMessage> pageParam = new Page<>(page, size);
        IPage<PrivateMessage> messages = privateMessageService.getOutbox(user.getId(), pageParam);
        
        // 转换为响应DTO
        List<PrivateMessageResponse> responseList = messages.getRecords().stream()
            .map(this::convertToResponse)
            .collect(Collectors.toList());
            
        Page<PrivateMessageResponse> responsePage = new Page<>(page, size, messages.getTotal());
        responsePage.setRecords(responseList);
        
        return CommonResult.success(responsePage);
    }
    
    @ApiOperation("发送私信")
    @PostMapping("/send")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<PrivateMessageResponse> sendMessage(@RequestBody SendMessageRequest request, HttpServletRequest httpRequest) {
        User sender = userService.getCurrentUser();
        
        // 确定接收者ID
        Long receiverId = request.getReceiverId();
        if (receiverId == null && request.getReceiverUsername() != null) {
            User receiver = userService.getUserByUsername(request.getReceiverUsername());
            if (receiver == null) {
                return CommonResult.error("接收者用户不存在");
            }
            receiverId = receiver.getId();
        }
        
        if (receiverId == null) {
            return CommonResult.error("请指定接收者");
        }
        
        // 创建私信对象
        PrivateMessage message = new PrivateMessage();
        message.setSenderId(sender.getId());
        message.setReceiverId(receiverId);
        message.setSubject(request.getSubject());
        message.setContent(request.getContent());
        message.setSentTime(LocalDateTime.now());
        message.setIsRead(false);
        message.setSenderDeleted(false);
        message.setReceiverDeleted(false);
        
        PrivateMessage sentMessage = privateMessageService.sendMessage(message);
        PrivateMessageResponse response = convertToResponse(sentMessage);
        
        return CommonResult.success(response);
    }
    
    @ApiOperation("标记为已读")
    @PutMapping("/{messageId}/read")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> markAsRead(@ApiParam("消息ID") @PathVariable Long messageId, HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        privateMessageService.markAsRead(messageId, user.getId());
        return CommonResult.success("标记成功");
    }
    
    @ApiOperation("删除私信")
    @DeleteMapping("/{messageId}")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<String> deleteMessage(@ApiParam("消息ID") @PathVariable Long messageId, HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        privateMessageService.deleteMessage(messageId, user.getId());
        return CommonResult.success("删除成功");
    }
    
    @ApiOperation("获取未读消息数量")
    @GetMapping("/unread-count")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<Integer> getUnreadCount(HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        Integer count = privateMessageService.getUnreadCount(user.getId());
        return CommonResult.success(count);
    }
    
    @ApiOperation("获取消息详情")
    @GetMapping("/{messageId}")
    @PreAuthorize("hasRole('USER')")
    public CommonResult<PrivateMessageResponse> getMessageDetail(@ApiParam("消息ID") @PathVariable Long messageId, HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        // 获取消息详情
        PrivateMessage message = privateMessageService.getMessageById(messageId, user.getId());
        if (message == null) {
            return CommonResult.error("消息不存在或无权访问");
        }
        
        PrivateMessageResponse response = convertToResponse(message);
        return CommonResult.success(response);
    }
    
    /**
     * 转换PrivateMessage为PrivateMessageResponse
     */
    private PrivateMessageResponse convertToResponse(PrivateMessage message) {
        PrivateMessageResponse response = new PrivateMessageResponse();
        response.setId(message.getId());
        response.setSenderId(message.getSenderId());
        response.setReceiverId(message.getReceiverId());
        response.setSubject(message.getSubject());
        response.setContent(message.getContent());
        response.setIsRead(message.getIsRead());
        response.setSenderDeleted(message.getSenderDeleted());
        response.setReceiverDeleted(message.getReceiverDeleted());
        response.setSentTime(message.getSentTime());
        response.setCreatedTime(message.getSentTime()); // 设置前端期望的字段
        response.setReadTime(message.getReadTime());
        
        // 获取发件人用户名
        User sender = userService.getUserById(message.getSenderId());
        if (sender != null) {
            response.setSenderUsername(sender.getUsername());
        }
        
        // 获取接收者用户名
        User receiver = userService.getUserById(message.getReceiverId());
        if (receiver != null) {
            response.setReceiverUsername(receiver.getUsername());
        }
        
        return response;
    }
} 